package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;
    @RequestMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session){

        R<Employee> r = employeeService.login(employee);

        if (r.getCode()==1){
            session.setAttribute("employee",r.getData());


        }
        return r;

    }

    @RequestMapping("/logout")
    public R<String> logout(HttpSession session){
        session.invalidate();
        return R.success(null);
    }
    @RequestMapping(method = RequestMethod.POST)
    public R<String> save(@RequestBody Employee employee,HttpSession session){

        Employee loginEmployee = (Employee) session.getAttribute("employee");

        employee.setCreateUser(loginEmployee.getId());
        employee.setUpdateUser(loginEmployee.getId());

        employeeService.save(employee);

        return R.success("添加成功");

    }
    @GetMapping("/page")
    public R<Page<Employee>> findByPage(Integer page, Integer pageSize, String name) {
        Page<Employee> pageObj = employeeService.findByPage(page, pageSize, name);

        return R.success(pageObj);
    }
    //修改员工状态
    @RequestMapping(method = RequestMethod.PUT)
    public R<String> update(@RequestBody Employee employee,HttpSession session) {

        Employee loginEmployee = (Employee) session.getAttribute("employee");

        employee.setUpdateUser(loginEmployee.getId());

        employeeService.update(employee);

        return R.success("修改成功");
    }

        //根据id查询员工对象
        @RequestMapping(value = "/{id}",method = RequestMethod.GET)
        public R<Employee> findById(@PathVariable long id) {
            //1.调用业务根据id获取员工对象
            Employee employee = employeeService.findById(id);

            //2.封装数据返回
            return R.success(employee);


        }


    }
